package com.idez.androiddelphi.model;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
//@Interceptors({ LogInterceptor.class })
public class UsuarioEJB implements UsuarioDAO {

	@PersistenceContext
	private EntityManager em;

	@Resource(mappedName = "java:/JmsXA")
	private ConnectionFactory connectionFactory;

	@Resource(mappedName = "java:/queue/test")
	private Destination destination;

	private Connection connection;
	private MessageProducer messageProducer;
	private Session session;

	@PostConstruct
	public void init() {
		try {
			connection = connectionFactory.createConnection();
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			messageProducer = session.createProducer(destination);
		} catch (JMSException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@PreDestroy
	public void destroy() {
		if (connection != null) {
			try {
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void salvar(Usuario u) {
		ObjectMessage message;
		try {
			message = session.createObjectMessage(u);
			messageProducer.send(message);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		em.persist(u);

	}

	@Override
	public void editar(Usuario u) {
		u = em.merge(u);

	}

	@Override
	public void excluir(Usuario u) {
		Usuario aRemover = em.find(Usuario.class, u.getId());
		em.remove(aRemover);

	}

	@Override
	public Usuario carregar(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Usuario buscarPorLogin(String login) {
		Query query = em
				.createQuery("Select u from Usuario u where u.login = :login");
		query.setParameter("login", login);
		return (Usuario) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Usuario> listar() {
		Query query = em.createQuery("Select u from Usuario u");
		return query.getResultList();
	}

}
